<template>
  <div class="login-bg">
    <div class="login-mask"></div>
    <el-form class="form-login" :model="users">
      <div class="logo-box">
        <img class="logo" src="@/assets/logo.png" alt="多转转" />
        <h1>系统登录</h1>
      </div>

      <el-form-item>
        <el-input v-model="users.username"
                  placeholder="请输入用户名"
                  clearable maxlength="16"></el-input>
      </el-form-item>

      <el-form-item>
        <el-input v-model="users.password"
                  placeholder="请输入密码"
                  clearable show-password maxlength="16"></el-input>
      </el-form-item>

      <el-form-item class="vercode-box">
        <el-input v-model="users.captcha"
                  placeholder="验证码"
                  maxlength="5"
                  class="input-verCode"></el-input>
        <img :src="captcha"
             class="img-verCode"
             @click="loadCaptcha"
             title="点击刷新验证码">
      </el-form-item>

      <el-form-item>
        <el-button class="btn-login" type="primary" round @click="onSubmit">登 录</el-button>
      </el-form-item>

      <el-form-item class="forget-password">
        <el-button type="text" @click="showForgetPasswordDialog">忘记密码?</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 忘记密码对话框 -->
  <el-dialog v-model="forgetPasswordDialogVisible" title="重置密码" width="500px">
    <el-form :model="resetPasswordForm" label-width="100px">
      <el-form-item label="用户名">
        <el-input v-model="resetPasswordForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="邮箱验证码">
        <el-input v-model="resetPasswordForm.emailCode" placeholder="请输入邮箱验证码">
          <template #append>
            <el-button @click="sendEmailCode" :disabled="isSendingCode || countdown > 0">
              {{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="新密码">
        <el-input v-model="resetPasswordForm.newPassword" type="password" placeholder="请输入新密码" />
      </el-form-item>
      <el-form-item label="确认密码">
        <el-input v-model="resetPasswordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="forgetPasswordDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitResetPassword">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import loginApi from '../api/login_api.js';
import { ElMessage } from 'element-plus';

const users = ref({
  username: '',
  password: '',
  captcha: '',
  key: ''
});
const captcha = ref('');
const router = useRouter();

// 忘记密码相关
const forgetPasswordDialogVisible = ref(false);
const resetPasswordForm = ref({
  username: '',
  emailCode: '',
  newPassword: '',
  confirmPassword: ''
});
const isSendingCode = ref(false);
const countdown = ref(0);
let timer = null;

onMounted(() => {
  localStorage.removeItem('token');
  //加载验证码
  loadCaptcha();
})

const onSubmit = async () => {
  const res = await loginApi.login(users.value);
  if(res){
    localStorage.setItem('token', res);
    //跳转
    router.push('/');
  }
}

const loadCaptcha = async () => {
  const res = await loginApi.captcha();
  users.value.key = res.key;
  captcha.value = res.base;
}

// 显示忘记密码对话框
const showForgetPasswordDialog = () => {
  resetPasswordForm.value = {
    username: '',
    emailCode: '',
    newPassword: '',
    confirmPassword: ''
  };
  forgetPasswordDialogVisible.value = true;
  countdown.value = 0;
  isSendingCode.value = false;
  if (timer) clearInterval(timer);
}

// 发送邮箱验证码
const sendEmailCode = async () => {
  if (!resetPasswordForm.value.username) {
    ElMessage.warning('请输入用户名');
    return;
  }
  if (isSendingCode.value) return;

  try {
    isSendingCode.value = true;
    await loginApi.sendEmailCode({ username: resetPasswordForm.value.username });

    countdown.value = 60;
    timer = setInterval(() => {
      if (countdown.value > 0) countdown.value--;
      else {
        clearInterval(timer);
        timer = null;
        isSendingCode.value = false;
      }
    }, 1000);
  } catch (error) {
    console.error(error);
    ElMessage.error('发送失败');
    isSendingCode.value = false;
  }
}

// 提交重置密码
const submitResetPassword = async () => {
  if (!resetPasswordForm.value.username || !resetPasswordForm.value.emailCode ||
      !resetPasswordForm.value.newPassword || !resetPasswordForm.value.confirmPassword) {
    ElMessage.warning('请完整填写信息');
    return;
  }

  if (resetPasswordForm.value.newPassword !== resetPasswordForm.value.confirmPassword) {
    ElMessage.error('两次输入的新密码不一致');
    return;
  }

  try {
    await loginApi.resetPassword({
      username: resetPasswordForm.value.username,
      emailCode: resetPasswordForm.value.emailCode,
      newPassword: resetPasswordForm.value.newPassword
    });

    ElMessage.success('密码重置成功，请重新登录');

    // 清理表单和倒计时
    resetPasswordForm.value = {
      username: '',
      emailCode: '',
      newPassword: '',
      confirmPassword: ''
    };
    countdown.value = 0;
    isSendingCode.value = false;
    if (timer) {
      clearInterval(timer);
      timer = null;
    }

    forgetPasswordDialogVisible.value = false;
  } catch (error) {
    console.error(error);
  }
}
</script>

<style scoped>
/* 背景：淡红渐变 + 半透明叠层 */
.login-bg {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #fef0f2, #ffe0e5, #f3efef);
  background-size: 400% 400%;
  animation: bgMove 12s ease infinite;
  position: relative;
}
@keyframes bgMove {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

.login-mask {
  position: absolute;
  inset: 0;
  background: rgba(0,0,0,0.15);
  backdrop-filter: blur(6px);
}

/* 表单卡片：圆滑玻璃 + 微浮动动画 */
.form-login {
  width: 360px;
  padding: 40px 32px;
  border-radius: 32px;
  background: linear-gradient(145deg, rgba(255,240,245,0.2), rgba(255,230,235,0.1));
  border: 1px solid rgba(255,192,203,0.25);
  box-shadow: 0 6px 20px rgba(182,45,45,0.15), 0 10px 30px rgba(182,45,45,0.1);
  backdrop-filter: blur(18px);
  z-index: 1;
  animation: fadeIn 0.8s ease, floatCard 6s ease-in-out infinite;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.form-login:hover {
  transform: translateY(-4px);
  box-shadow: 0 10px 25px rgba(182,45,45,0.2), 0 15px 35px rgba(182,45,45,0.12);
}

/* LOGO + 标题 */
.logo-box {
  text-align: center;
  margin-bottom: 25px;
  position: relative;
}
.logo {
  width: 70px;
  height: 70px;
  margin-bottom: 12px;
  border-radius: 50%;
  background: rgba(255,192,203,0.25);
  padding: 10px;
  object-fit: contain;
  box-shadow: 0 4px 15px rgba(182,45,45,0.15);
}
h1 {
  font-size: 22px;
  margin: 0;
  font-weight: 600;
  color: rgba(244, 64, 64, 0.35);
}

/* 输入框 & 验证码行 */
.el-input, .el-button {
  border-radius: 20px;
  transition: all 0.3s ease;
}
.el-input:focus-within {
  box-shadow: 0 0 10px rgba(182,45,45,0.4);
}

.vercode-box {
  display: flex;
  align-items: center;
}
.input-verCode {
  flex: 1;
  margin-right: 12px;
}
.img-verCode {
  width: 100px;
  height: 36px;
  border-radius: 12px;
  cursor: pointer;
  border: 1px solid rgba(182,45,45,0.5);
  background: #fff;
  transition: all 0.3s;
}
.img-verCode:hover {
  transform: scale(1.05);
  border-color: #d65a6c;
}

/* 按钮 */
.btn-login {
  width: 100%;
  font-size: 16px;
  padding: 12px 0;
  border-radius: 25px;
  background: linear-gradient(135deg, #ff7f9e, #d65a6c);
  box-shadow: 0 6px 15px rgba(182,45,45,0.25);
  transition: all 0.3s;
}
.btn-login:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(182,45,45,0.35);
}

.forget-password {
  text-align: center;
  margin-bottom: 0;
}

.forget-password .el-button {
  font-size: 14px;
  padding: 0;
  border-radius: 0;
}

/* 动画 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}
@keyframes floatCard {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-6px); }
}
</style>
